<template>
  <div class="category-container">
    <div class="page-header">
      <h1>🗂️ Fruit Category Management</h1>
      <el-button type="primary" :icon="Plus" @click="showAddDialog">Add Category</el-button>
    </div>

    <!-- 分类列表 -->
    <el-table 
      v-loading="loading"
      :data="categories" 
      style="width: 100%" 
      stripe
    >
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column label="Icon" width="80">
        <template #default="scope">
          <span style="font-size: 24px">{{ scope.row.icon || '📦' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="Category Name" width="200" />
      <el-table-column prop="description" label="Description" />
      <el-table-column label="Operations" width="200" fixed="right">
        <template #default="scope">
          <el-button size="small" type="primary" :icon="Edit" @click="handleEdit(scope.row)">
            Edit
          </el-button>
          <el-button size="small" type="danger" :icon="Delete" @click="handleDelete(scope.row)">
            Delete
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 空状态 -->
    <el-empty v-if="!loading && categories.length === 0" description="No category data" />

    <!-- 添加/编辑对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="dialogTitle" 
      width="500px"
      @close="resetForm"
    >
      <el-form 
        ref="formRef"
        :model="form" 
        :rules="formRules"
        label-width="120px"
      >
        <el-form-item label="Category Name" prop="name">
          <el-input v-model="form.name" placeholder="Please enter category name" />
        </el-form-item>
        <el-form-item label="Description">
          <el-input v-model="form.description" type="textarea" :rows="3" placeholder="Please enter description" />
        </el-form-item>
        <el-form-item label="Icon">
          <el-input v-model="form.icon" placeholder="Emoji icon (e.g. 🍎)" maxlength="2" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">Cancel</el-button>
        <el-button type="primary" @click="handleSave" :loading="saveLoading">Confirm</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus, Edit, Delete } from '@element-plus/icons-vue';
import { categoryAPI } from '@/api';

const categories = ref([]);
const loading = ref(false);
const saveLoading = ref(false);

const dialogVisible = ref(false);
const dialogTitle = ref('Add Category');
const formRef = ref(null);
const isEdit = ref(false);
const editId = ref(null);

const form = ref({
  name: '',
  description: '',
  icon: ''
});

const formRules = {
  name: [
    { required: true, message: 'Please enter category name', trigger: 'blur' }
  ]
};

// 加载分类列表
const loadCategories = async () => {
  loading.value = true;
  try {
    const response = await categoryAPI.getList();
    
    if (response.success) {
      categories.value = response.data;
    }
  } catch (error) {
    console.error('Load categories failed:', error);
    const errorMessage = error.response?.data?.message || error.message || 'Failed to load categories';
    ElMessage.error(errorMessage);
  } finally {
    loading.value = false;
  }
};

// 显示添加对话框
const showAddDialog = () => {
  dialogTitle.value = 'Add Category';
  isEdit.value = false;
  editId.value = null;
  resetForm();
  dialogVisible.value = true;
};

// 编辑
const handleEdit = (row) => {
  dialogTitle.value = 'Edit Category';
  isEdit.value = true;
  editId.value = row.id;
  form.value = {
    name: row.name,
    description: row.description || '',
    icon: row.icon || ''
  };
  dialogVisible.value = true;
};

// 保存
const handleSave = async () => {
  if (!formRef.value) return;
  
  await formRef.value.validate(async (valid) => {
    if (!valid) return;
    
    saveLoading.value = true;
    try {
      let response;
      
      if (isEdit.value) {
        // 更新
        response = await categoryAPI.update(editId.value, form.value);
      } else {
        // 创建
        response = await categoryAPI.create(form.value);
      }
      
      if (response.success) {
        ElMessage.success(response.message || 'Saved successfully');
        dialogVisible.value = false;
        loadCategories();
      }
    } catch (error) {
      console.error('Save failed:', error);
      const errorMessage = error.response?.data?.message || error.message || 'Save failed';
      ElMessage.error(errorMessage);
    } finally {
      saveLoading.value = false;
    }
  });
};

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `Are you sure you want to delete "${row.name}"?`, 
    'Confirm', 
    {
      confirmButtonText: 'Confirm',
      cancelButtonText: 'Cancel',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const response = await categoryAPI.delete(row.id);
      
      if (response.success) {
        ElMessage.success(`"${row.name}" deleted successfully`);
        loadCategories();
      }
    } catch (error) {
      console.error('Delete failed:', error);
      const errorMessage = error.response?.data?.message || error.message || 'Delete failed';
      ElMessage.error(errorMessage);
    }
  }).catch(() => {});
};

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  form.value = {
    name: '',
    description: '',
    icon: ''
  };
};

// 页面加载时获取数据
onMounted(() => {
  loadCategories();
});
</script>

<style scoped>
.category-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0;
  font-size: 28px;
  color: #333;
}
</style>

